import os
from datetime import timedelta
from pathlib import Path

# ================================================= #
# ****************** DJANGO 配置 ******************* #
# ================================================= #

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-p0-q1cv8(v_3ze8l2q-e9^&=jq=l-4617rw@^%t3g5*h+&t4no'

ALLOWED_HOSTS = ['*']

AUTH_USER_MODEL = 'account.User'

INSTALLED_APPS = [
    'django_comment_migrate',
    'simpleui',
    'django_filters',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework_simplejwt.token_blacklist',
    'account.apps.AccountConfig',
    'audit.apps.AuditConfig',
    'permissions.apps.PermissionsConfig',
    'file_manage.apps.FileManageConfig',
    'dictionary.apps.DictionaryConfig',
    'drf_yasg'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'utils.middlewares.LogMiddleWare.LogRequestCollectMiddleware',
    'utils.middlewares.LogMiddleWare.AuditLogMiddleware',
    'utils.middlewares.LogMiddleWare.AutoLogMiddleware',
    'utils.middlewares.LogMiddleWare.LogResponseCollectMiddleware'
]

ROOT_URLCONF = 'django_template_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'wsgi.application'

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_TZ = True

STATIC_URL = 'static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# noinspection PyUnresolvedReferences
STATIC_ROOT = os.path.join(BASE_DIR, "static")

# ================================================= #
# ********************* LOG 配置 ******************* #
# ================================================= #
LOG_PATH = Path(os.path.join(BASE_DIR, 'logs')).resolve()

if not LOG_PATH.is_dir():
    LOG_PATH.mkdir(exist_ok=True, parents=True)


def get_default_log_handler(level, filename):
    return {
        'level': level,
        'class': 'logging.handlers.TimedRotatingFileHandler',
        'filename': LOG_PATH.joinpath(filename),
        'formatter': 'standard',
        'filters': ['request'],
        'when': 'midnight',
        'interval': 1,
        'backupCount': 365,
        'encoding': 'utf-8'
    }


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
        'request': {
            # 自定义的filter
            '()': 'utils.middlewares.LogMiddleWare.RequestFilter',
        },
        'db': {
            # 自定义的filter
            '()': 'utils.middlewares.LogMiddleWare.DbLogFilter',
        }
    },
    'formatters': {
        # 详细的日志格式
        # [时间][log级别][任务名][request_id][request_ip|request_method|request_path] - msg内容
        'standard': {
            'format': '[%(asctime)s][%(levelname)s][%(name)s][%(request_id)s]'
                      '[%(request_ip)s|%(request_method)s|%(request_path)s] - '
                      '%(message)s'
        },
    },
    'handlers': {
        'common_file_handler': get_default_log_handler('DEBUG', 'common.log'),
        'db_file_handler': get_default_log_handler('DEBUG', 'db.log'),
        'error': get_default_log_handler('ERROR', 'error.log'),
        'operation_handler': {
            'level': 'DEBUG',
            'class': 'utils.handlers.log_handlers.OperationDBHandler',
            'formatter': 'standard',
            'filters': ['db']
        },
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true', 'request'],
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'common': {
            'handlers': ['common_file_handler', 'console'],
            'propagate': True,
            'level': 'INFO',
        },
        'django.db.backends': {
            'handlers': ['db_file_handler'],
            'propagate': True,
            'level': 'INFO',
        },
        'error': {
            'handlers': ['error', 'console'],
            'propagate': True,
            'level': 'ERROR',
        },
        'operation_auto': {
            'handlers': ['operation_handler'],
            'propagate': True,
            'level': 'INFO',
        },
        'operation': {
            'handlers': ['operation_handler'],
            'propagate': True,
            'level': 'INFO',
        },
    }
}

# ================================================= #
# *************** REST_FRAMEWORK配置 *************** #
# ================================================= #
REST_FRAMEWORK = {
    # 时间序列化格式
    'DATETIME_FORMAT': '%Y-%m-%d %H:%M:%S',
    'DATE_FORMAT': '%Y-%m-%d',
    'TIME_FORMAT': '%H:%M:%S',
    # 'DEFAULT_PERMISSION_CLASSES': REST_FRAMEWORK_DEFAULT_PERMISSION_CLASSES,
    "DEFAULT_PERMISSION_CLASSES": ["utils.addons.permissions_addon.DefaultPermissionBackend"],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    "DEFAULT_FILTER_BACKENDS": (
        # 'django_filters.rest_framework.DjangoFilterBackend',
        # 'utils.mixins.filters.AllLookupsFilterBackend',
    ),
    'DEFAULT_PAGINATION_CLASS': 'utils.mixins.common_mixins.pagination.CustomPageNumberPagination',
    'EXCEPTION_HANDLER': 'utils.handlers.exception_handler.CustomExceptionHandler',  # 自定义的异常处理
}

# ================================================= #
# *************** SIMPLE_JWT配置 *************** #
# ================================================= #
SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(days=1),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    "TOKEN_OBTAIN_SERIALIZER": "utils.mixins.common_mixins.tokens.CustomTokenObtainPairSerializer",
    "TOKEN_REFRESH_SERIALIZER": "utils.mixins.common_mixins.tokens.CustomTokenRefreshSerializer",
}


# ================================================= #
# ***************     SWAGGER配置    *************** #
# ================================================= #
SWAGGER_SETTINGS = {
    'DEFAULT_GENERATOR_CLASS': 'drf_yasg.generators.OpenAPISchemaGenerator',
    'DEFAULT_AUTO_SCHEMA_CLASS': 'utils.handlers.swagger.CustomActionAutoSchema',
    'DEFAULT_FIELD_INSPECTORS': [
        'drf_yasg.inspectors.CamelCaseJSONFilter',
        'drf_yasg.inspectors.RecursiveFieldInspector',
        'drf_yasg.inspectors.ReferencingSerializerInspector',
        'drf_yasg.inspectors.ChoiceFieldInspector',
        'drf_yasg.inspectors.FileFieldInspector',
        'drf_yasg.inspectors.DictFieldInspector',
        'drf_yasg.inspectors.JSONFieldInspector',
        'drf_yasg.inspectors.HiddenFieldInspector',
        'drf_yasg.inspectors.RelatedFieldInspector',
        'drf_yasg.inspectors.SerializerMethodFieldInspector',
        'drf_yasg.inspectors.SimpleFieldInspector',
        'drf_yasg.inspectors.StringDefaultFieldInspector',
    ],
    'DEFAULT_FILTER_INSPECTORS': [
        'drf_yasg.inspectors.DrfAPICompatInspector',
        'drf_yasg.inspectors.CoreAPICompatInspector',
    ],
    'DEFAULT_PAGINATOR_INSPECTORS': [
        'drf_yasg.inspectors.DjangoRestResponsePagination',
        'drf_yasg.inspectors.DrfAPICompatInspector',
        'drf_yasg.inspectors.CoreAPICompatInspector',
    ],
    'DEFAULT_SPEC_RENDERERS': [
        'drf_yasg.renderers.SwaggerYAMLRenderer',
        'drf_yasg.renderers.SwaggerJSONRenderer',
        'drf_yasg.renderers.OpenAPIRenderer',
    ],
    'EXCLUDED_MEDIA_TYPES': ['html'],
    'DEFAULT_INFO': None,
    'DEFAULT_API_URL': None,
    'USE_SESSION_AUTH': True,
    'SECURITY_DEFINITIONS': {
        'Basic': {
            'type': 'basic'
        }
    },
    'SECURITY_REQUIREMENTS': None,
    'SPEC_URL': None,
    'VALIDATOR_URL': '',
    'PERSIST_AUTH': False,
    'FETCH_SCHEMA_WITH_QUERY': True,
    'OPERATIONS_SORTER': None,
    'TAGS_SORTER': None,
    'DOC_EXPANSION': 'list',
    'DEEP_LINKING': False,
    'SHOW_EXTENSIONS': True,
    'DEFAULT_MODEL_RENDERING': 'model',
    'DEFAULT_MODEL_DEPTH': 3,
    'SHOW_COMMON_EXTENSIONS': True,
    'OAUTH2_REDIRECT_URL': None,
    'OAUTH2_CONFIG': {},
    'SUPPORTED_SUBMIT_METHODS': [
        'get',
        'put',
        'post',
        'delete',
        'options',
        'head',
        'patch',
        'trace'
    ],
    'DISPLAY_OPERATION_ID': True,
}
